package ar.edu.sccs.model.loader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import ar.edu.sccs.dao.DaoModule;
import ar.edu.sccs.entities.Case;
import ar.edu.sccs.model.loader.dto.DataClazz;
import ar.edu.sccs.monitoring.exception.SccsGenericException;
import ar.edu.sccs.util.Constants;
import ar.edu.sccs.util.FiltroDeArchivo;
import ar.edu.sccs.util.ObjectInStream;
import ar.edu.sccs.util.ObjectOutStream;

public class CoreLoader {

	static Logger logger = Logger.getLogger(CoreLoader.class);

	private DaoModule daoModule = new DaoModule();

	private void checkRepository() {

	}

	public void loadProject() {
		ObjectInStream inputFile = new ObjectInStream();

		List<DataClazz> dataClazz = new ArrayList<DataClazz>();
		try {
			dataClazz = inputFile.readFile(Constants.Loader.FILE_DIR + Constants.Loader.FILE_NAME);
		} catch (SccsGenericException e) {
			logger.error("CoreLoader.loadProject ERROR", e);
		}

		List<Case> dataCases = ReflectionLoader.loadCaseInfo(dataClazz);
		try {
			daoModule.loadCases(dataCases);
		} catch (SccsGenericException e) {
			logger.error("CoreLoader.loadProject ERROR", e);
		}
	}

	private void createMetaDataFile() {
		logger.debug("CoreLoader.createMetaDataFile - BEGIN");

		File clazzDirectory = new File(loadProjectDirectory() + "\\bin");
		List<File> clazzFileList = loadProjectFiles(clazzDirectory);
		List<DataClazz> clazzData = new ArrayList<DataClazz>();
		for (File clazzFile : clazzFileList) {
			clazzData.add(ReflectionLoader.getClassInfo(clazzFile, clazzDirectory));
		}

		ObjectOutStream outputFile = new ObjectOutStream();
		try {
			outputFile.writeFile(Constants.Loader.FILE_DIR + Constants.Loader.FILE_NAME, clazzData);
		} catch (Exception e) {
			logger.error("CoreLoader.createMetaDataFile ERROR", e);
		}

		logger.debug("CoreLoader.createMetaDataFile - END");
	}

	public static void main(String[] args) {
		CoreLoader coreLoader = new CoreLoader();
		coreLoader.createMetaDataFile();
	}

	private File loadProjectDirectory() {
		File projectDir = new File(System.getProperty("user.dir"));
		logger.debug("CoreLoader.loadProjectData from [" + projectDir + "]");

		return projectDir;
	}

	private List<File> loadProjectFiles(File directory) {
		List<File> clazzFileList = new ArrayList<File>();

		for (File file : directory.listFiles(new FiltroDeArchivo("class", "COMMENT"))) {
			if (file.isFile())
				clazzFileList.add(file);
			else
				clazzFileList.addAll(this.loadProjectFiles(file));
		}

		return clazzFileList;
	}
}
